//
//  ContactVC.m
//  timelyRain
//
//  Created by Jiafei Wei on 16/7/23.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "ContactVC.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "TContact.h"
#import "ChineseString.h"
#import "ContactCell.h"
#import "ShowView.h"
#import "LewPopupViewController.h"
#import "RealtimeSearchUtil.h"
#import "DbManage.h"
#import "AddMark.h"
#import "ChatViewController.h"
#import "OpenMyGroup.h"
#import "TContactSearch.h"
#import "ContactPersonInfo.h"
#import "ContactPersonO.h"
#import "HttpTool.h"
#import "MJExtension.h"
#import "ChatDemoHelper.h"
@import Contacts;
@interface ContactVC()<UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating,ContactCellDelegate,UISearchBarDelegate,ABNewPersonViewControllerDelegate>
{
    NSMutableArray *nameArray;
    NSMutableArray *contactDataArray;
    ShowView *show;
}
@property (strong, nonatomic) NSMutableArray *sectionTitles;
@property (strong, nonatomic) NSMutableArray *contactsSource;

@property(nonatomic,strong)NSMutableArray *indexArray;
@property(nonatomic,strong)NSMutableArray *searchArr;
@property(nonatomic,strong)NSMutableArray *letterResultArr;
@property (nonatomic,strong)NSMutableArray *searchArray;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic ,strong)UISearchController *searchVC;
@end

@implementation ContactVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [_table setAllowsSelectionDuringEditing:YES];
    [self arrayCreate];
    [self addSearchVC];
    [self _sortDataArray];
    [self getFriends];
}
-(void)getFriends{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSArray *userlist = [[EMClient sharedClient].contactManager getContactsFromServerWithError:nil];
        //NSLog(@"获取成功 -- %@",userlist);
    });
}
-(void)arrayCreate{
    _searchArray =[NSMutableArray array];
    _contactsSource = [[DbManage shareDbManage]queryConatctArray];
    _sectionTitles = [NSMutableArray array];
    nameArray = [NSMutableArray array];
    contactDataArray = [NSMutableArray array];
    _indexArray =[NSMutableArray array];
    _letterResultArr =[NSMutableArray array];
    _table.delegate=self;
    _table.dataSource=self;
    [_table setAllowsSelectionDuringEditing:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    _searchVC.active=NO;
    self.navigationController.navigationBarHidden =NO;
}

- (void)cellImageViewLongPressAtIndexPath:(NSIndexPath *)indexPath;{
//    ABNewPersonViewController *p =[[ABNewPersonViewController alloc]init];
//    p.newPersonViewDelegate =self;
//    [self.navigationController pushViewController:p animated:YES];
//    ABNewPersonViewController *p =[[ABNewPersonViewController alloc]init];
//    p.newPersonViewDelegate =self;
//    [self presentViewController:p animated:YES completion:nil];
//    show =[ShowView headerView];
//    [self lew_presentPopupView:show animation:[LewPopupViewAnimationSpring new] dismissed:^{
//        NSLog(@"动画结束");
//    }];
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.indexArray;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *key = [self.indexArray objectAtIndex:section];
    return key;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_searchVC.active) {//搜索的时候
        return 1;
    }else{
        return [self.indexArray count] +1;//只有一组啊
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchVC.active) {//搜索的时候
        return _searchArray.count;
    }else{
        if (section == 0) {
            return 2;
        }
        return [[self.letterResultArr objectAtIndex:(section - 1)] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_searchVC.active) {
        ContactCell *contactCell =[ContactCell setContactCellWithTableView:tableView];
        contactCell.delegate =self;
        contactCell.indexPath =indexPath;
        TContact *t =[_searchArray objectAtIndex:indexPath.row];
        contactCell.data =t;
        [self setheadPic:t.phone with:contactCell.image];
        return contactCell;
    }else{
        if(indexPath.section == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];//为空的cell
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                              reuseIdentifier:@"Cell"];
            }
            if (indexPath.row == 0) {
                cell.textLabel.text =@"我的群组";
            }else{
                cell.textLabel.text =@"所有联系人";
            }
            return cell;
        }else{
            ContactCell *contactCell =[ContactCell setContactCellWithTableView:tableView];
            contactCell.delegate =self;
            contactCell.indexPath =indexPath;
            TContact *t =[[self.letterResultArr objectAtIndex:(indexPath.section-1)]objectAtIndex:indexPath.row];
            contactCell.data =t;
            [self setheadPic:t.phone with:contactCell.image];
            return contactCell;
        }
    
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        UILabel *lab = [UILabel new];
        lab.backgroundColor = [UIColor groupTableViewBackgroundColor];
        lab.text = @"";
        lab.textColor = [UIColor blackColor];
        return lab;
    }else{
        TContactSearch *search =[TContactSearch headerView];
        search.name.text =[self.indexArray objectAtIndex:(section-1)];
        return search;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 49.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }
    return 33;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_searchVC.active){
         TContact *t =[_searchArray objectAtIndex:indexPath.row];
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:t.phone conversationType:EMConversationTypeChat];
        chatController.title =t.phone;
        chatController.phoneValue=t.phone;
        chatController.nameValue=t.name;
        [self.navigationController pushViewController:chatController animated:YES];
    }else{
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            OpenMyGroup *g =[[OpenMyGroup alloc]init];
            [self.navigationController pushViewController:g animated:YES];
        }
    }else{
        //先把数据给传到手表先
        TContact *t =[[self.letterResultArr objectAtIndex:(indexPath.section-1)]objectAtIndex:indexPath.row];
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:t.phone conversationType:EMConversationTypeChat];
        //    ChartVC *chart =[[ChartVC alloc]init];
        //    chart.title =@"18927482671";
        //    ChartVC *chatVC = [[ChartVC alloc]initWithConversationChatter:@"18927482671"
        //                                  conversationType:EMConversationTypeChat];
        chatController.title =t.phone;
        chatController.phoneValue=t.phone;
        chatController.nameValue=t.name;
        [self.navigationController pushViewController:chatController animated:YES];
    }
    }
}

-(void)addSearchVC
{
        _searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchVC.searchResultsUpdater = self;
        _searchVC.dimsBackgroundDuringPresentation = NO;
        _searchVC.hidesNavigationBarDuringPresentation = NO;
        _searchVC.searchBar.frame = CGRectMake(self.searchVC.searchBar.frame.origin.x, self.searchVC.searchBar.frame.origin.y, self.searchVC.searchBar.frame.size.width, 44.0);
        [self.searchVC.searchBar setImage:[UIImage imageNamed:@"搜索"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    self.searchVC.searchBar.delegate =self;
    //[self.view addSubview:self.searchVC.searchBar];
   _table.tableHeaderView = self.searchVC.searchBar;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    __weak typeof(self) weakSelf = self;
    if (_letterResultArr.count==0) {
        NSLog(@"操你奶");
    }
    NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",searchText];
    NSArray *aa =[_contactsSource filteredArrayUsingPredicate:filterPredicate];
    for (TContact *a in aa) {
        NSLog(@"name =====%@",a.name);
    }
    [_searchArray removeAllObjects];
    [_searchArray addObjectsFromArray:aa];
    [_table reloadData];
}


- (void)_sortDataArray
{
    [self.letterResultArr removeAllObjects];
    [self.indexArray removeAllObjects];
    
    //建立索引的核心, 返回27，是a－z和＃
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    NSArray *ddd=[indexCollation sectionTitles];
    [self.indexArray addObjectsFromArray:[indexCollation sectionTitles]];
    
    NSInteger highSection = [self.indexArray count];
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i < highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }
    
    //按首字母分组
    for (TContact *buddy in _contactsSource) {
        NSString *firstLetter = [EaseChineseToPinyin pinyinFromChineseString:buddy.name];
        NSInteger section = [indexCollation sectionForObject:[firstLetter substringToIndex:1] collationStringSelector:@selector(uppercaseString)];
        NSMutableArray *array = [sortedArray objectAtIndex:section];
        [array addObject:buddy];
    }
    
//    //每个section内的数组排序
//    for (int i = 0; i < [sortedArray count]; i++) {
//        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(EaseUserModel *obj1, EaseUserModel *obj2) {
//            NSString *firstLetter1 = [EaseChineseToPinyin pinyinFromChineseString:obj1.buddy];
//            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
//            
//            NSString *firstLetter2 = [EaseChineseToPinyin pinyinFromChineseString:obj2.buddy];
//            firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
//            
//            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
//        }];
//        
//        
//        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
//    }
    //去掉空的section
    for (NSInteger i = [sortedArray count] - 1; i >= 0; i--) {
        NSArray *array = [sortedArray objectAtIndex:i];
        if ([array count] == 0) {
            [sortedArray removeObjectAtIndex:i];
            [self.indexArray removeObjectAtIndex:i];
        }
    }
    [self.letterResultArr addObjectsFromArray:sortedArray];
    [_table reloadData];
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(nullable ABRecordRef)person;{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
     self.navigationController.navigationBarHidden =YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
     _searchVC.active=NO;
    [_table reloadData];
}
-(void)setheadPic:(NSString *)number with:(UIImageView *)imageView{
    NSMutableArray *array =[[DbManage shareDbManage] queryPersonInfoByUserId:number];
    if (array.count!=0) {
       ContactPersonInfo *info = [array objectAtIndex:0];
        if (info.head_pic!=nil) {
            [imageView sd_setImageWithURL:[NSURL URLWithString:info.head_pic]];
        }
    }else{
    
    }
}
-(void)refrshContact{
     NSLog(@"难道是没有刷新的意思吗？");
    [_contactsSource removeAllObjects];
    [_contactsSource addObjectsFromArray:[[DbManage shareDbManage]queryConatctArray]];
    [self _sortDataArray];
}
@end
